package org.dromara.run.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.service.IMemberService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.run.domain.RunList;
import org.dromara.run.domain.bo.RunListBo;
import org.dromara.run.domain.bo.ScheduleBo;
import org.dromara.run.domain.vo.RunListVo;
import org.dromara.run.service.IRunListService;
import org.dromara.run.service.IScheduleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.run.domain.bo.ScoreBo;
import org.dromara.run.domain.vo.ScoreVo;
import org.dromara.run.domain.Score;
import org.dromara.run.mapper.ScoreMapper;
import org.dromara.run.service.IScoreService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 阳光跑成绩表Service业务层处理
 *
 * @author chl
 * @date 2024-08-30
 */
@RequiredArgsConstructor
@Service
public class ScoreServiceImpl implements IScoreService {

    private final ScoreMapper baseMapper;

    private final IRunListService iRunListService;
    private final IScheduleService iScheduleService;
    private final IMemberService memberService;

    /**
     * 查询阳光跑成绩表
     */
    @Override
    public ScoreVo queryById(Long scoreId){
        ScoreVo scoreVo = baseMapper.selectVoById(scoreId);
        if (scoreVo != null) {
            MemberVo memberVo = memberService.queryByIdNumber(scoreVo.getMemberId(), scoreVo.getTenantId());
            scoreVo.setMemberInfo(memberVo);
        }
        return scoreVo;
    }

    /**
     * 查询阳光跑成绩表列表
     */
    @Override
    public TableDataInfo<ScoreVo> queryPageList(ScoreBo bo, PageQuery pageQuery) {
        QueryWrapper<Score> lqw = buildQueryWrapper(bo);
        Page<ScoreVo> result = baseMapper.selectScoreList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询阳光跑成绩表列表
     */
    @Override
    public List<ScoreVo> queryList(ScoreBo bo) {
        QueryWrapper<Score> lqw = buildQueryWrapper(bo);
        return baseMapper.selectScoreList(lqw);
    }

    private QueryWrapper<Score> buildQueryWrapper(ScoreBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<Score> lqw = new QueryWrapper<>();
        lqw.eq(bo.getScoreId()!=null, "prs.score_id", bo.getScoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getMemberId()), "prs.member_id", bo.getMemberId());
        lqw.eq(StringUtils.isNotBlank(bo.getScheduleId()), "prs.schedule_id", bo.getScheduleId());
        lqw.eq(bo.getTotalRuns() != null, "prs.total_runs", bo.getTotalRuns());
        lqw.eq(bo.getValidRuns() != null, "prs.valid_runs", bo.getValidRuns());
        lqw.eq(bo.getMorningRuns() != null, "prs.morning_runs ", bo.getMorningRuns());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), "pmi.name", bo.getStudentName());
        lqw.eq(StringUtils.isNotBlank(bo.getYears()), "pbtc.years", bo.getYears());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getClassId()), "pmi.class_id", bo.getClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalId()), "sd1.dept_id", bo.getProfessionalId());
        lqw.eq(StringUtils.isNotBlank(bo.getCollegeId()), "sd2.dept_id", bo.getCollegeId());
        return lqw;
    }

    /**
     * 新增阳光跑成绩表
     */
    @Override
    public Boolean insertByBo(ScoreBo bo) {
        Score add = MapstructUtils.convert(bo, Score.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setScoreId(add.getScoreId());
        }
        return flag;
    }

    /**
     * 修改阳光跑成绩表
     */
    @Override
    public Boolean updateByBo(ScoreBo bo) {
        Score update = MapstructUtils.convert(bo, Score.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Score entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除阳光跑成绩表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bachCreteScore(ScheduleBo bo) {
        RunListBo runListBo=new RunListBo();
        runListBo.setScheduleId(bo.getScheduleId().toString());
        runListBo.setIsFree("0");
        List<RunListVo> runListVos = iRunListService.queryList(runListBo);
        if(CollectionUtils.isEmpty(runListVos)){
            throw new ServiceException("发布计划失败,请先生成名单");
        }
        List<Score> scoreBoList = runListVos.stream().map(x -> {
            Score score=new Score();
            score.setMemberId(x.getMemberId());
            score.setTenantId(x.getTenantId());
            score.setScheduleId(bo.getScheduleId().toString());
            return score;
        }).collect(Collectors.toList());
        boolean insertBatch = baseMapper.insertBatch(scoreBoList);
        if(!insertBatch){
            throw new ServiceException("发布计划失败");
        }
        bo.setStatus("2");
        Boolean aBoolean = iScheduleService.updateByBo(bo);
        return aBoolean;
    }

    @Override
    public Boolean deleteWithBo(ScoreBo bo) {
        QueryWrapper<Score> queryWrapper=buildQueryWrapper(bo);
        return baseMapper.delete(queryWrapper)>0;
    }

    @Override
    public ScoreVo selectScoreInfo(ScoreBo bo) {
        QueryWrapper<Score> queryWrapper=buildQueryWrapper(bo);
        return baseMapper.selectVoOne(queryWrapper);
    }
}
